from django.shortcuts import render, redirect
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from django.http import JsonResponse
from django.template.loader import render_to_string
from django.utils.timezone import localtime

from .models import Comment
from .forms import CommentForm
from mysite.utils import EmailSender


def add_comment(request):
    referer = request.META.get('HTTP_REFERER', reverse('home'))
    comment_form = CommentForm(request.POST, user=request.user)
    data = {}
    if comment_form.is_valid():
        comment = Comment()
        comment.content_object = comment_form.cleaned_data['model_obj']
        comment.text = comment_form.cleaned_data['text']
        comment.user = comment_form.cleaned_data['user']
        parent = comment_form.cleaned_data['parent']
        # 如果这个是回复
        if parent is not None:
            comment.parent = parent
            comment.reply_user = parent.user
            comment.root = parent.root if parent.root is not None else parent
        comment.save()

        # 异步发送邮件通知
        if comment.parent is None:
            # 评论
            subject = '有人回复了你~'
            message = ''
            email_to = comment.content_object.author.email
            context = {}
            context['user'] = comment.user
            context['content'] =  comment.text
            context['time'] = comment.comment_time
            context['url'] = request.build_absolute_uri(comment.content_object.get_url())
            html_message = render_to_string('comment/comment_notification.html', context)
        else:
            # 回复
            subject = '有人回复了你~'
            message = ''
            email_to = comment.reply_user.email
            context = {}
            context['user'] = comment.user
            context['content'] = comment.text
            context['time'] = comment.comment_time
            context['url'] = request.build_absolute_uri(comment.content_object.get_url())
            html_message = render_to_string('comment/comment_notification.html', context)
        email_sender = EmailSender(subject, message, email_to, html_message)
        email_sender.start()

        data['status'] = 'SUCCESS'
        data['username'] = comment.user.get_nickname_or_username()
        data['comment_time'] = localtime(comment.comment_time).strftime("%Y-%m-%d %H:%M:%S")
        data['text'] = comment.text
        # 新加评论对象的content_type名称
        data['content_type'] = ContentType.objects.get_for_model(comment).model
        # 新加评论的主键
        data['pk'] = comment.pk
        if parent is not None:
            data['reply_username'] = parent.user.get_nickname_or_username()
            data['root_pk'] = comment.root.pk
    else:
        data['status'] = 'ERROR'
        data['message'] = list(comment_form.errors.values())[0][0]
    return JsonResponse(data)
    '''
        return render(request, 'error.html', \
                {'message': comment_form.errors, 'redirect_url': referer})'''